package com.in.controller;

import com.in.dto.LoginDto;
import com.in.entity.InUser;
import com.in.service.InUserService;
import com.in.utils.CommonConstant;
import com.in.utils.JwtUtil;
import com.in.utils.Result;
import com.in.utils.StatusCode;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @ClassName LoginController
 * @Description 登录
 * @Author liulianjia
 * @Date 2024/11/26 16:22
 */
@Slf4j
@Validated
@RestController
public class LoginController {

    @Resource
    private InUserService userService;

    /**
     * @Author liulianjia
     * @Description 用户登录
     * @Date 2024/11/26 16:24
     **/
    @PostMapping("/login")
    public Result login(@Valid @RequestBody LoginDto dto, HttpServletRequest request) throws IOException {
        if ("yzm".equals(dto.getType()) && StringUtils.isBlank(dto.getCode())) {
            return Result.err(StatusCode.ERROR_CODE, "参数错误，请参考文档！");
        } else if ("password".equals(dto.getType()) && StringUtils.isBlank(dto.getPassword())) {
            return Result.err(StatusCode.ERROR_CODE, "参数错误，请参考文档！");
        } else {
            return userService.login(dto, request);
        }
    }

    /**
     * @Author liulianjia
     * @Description 发送验证码
     * @Date 2024/12/2 14:33
     **/
    @PostMapping("/getYzm")
    public Result getYzm(@Valid @RequestBody LoginDto dto) throws MessagingException, UnsupportedEncodingException {
        boolean f = userService.getYzm(dto);
        return f ? Result.success("发送成功") : Result.err(StatusCode.ERROR, "发送失败,请稍后再试！");
    }

    /**
     * @Author liulianjia
     * @Description 登出
     * @Date 2024/12/4 15:14
     **/
    @PostMapping("/login/out")
    public Result logout(@RequestHeader(CommonConstant.ACCESS_TOKEN) String token) {
        boolean f = userService.loginOut(token);
        return f ? Result.success("登出成功") : Result.err(StatusCode.ERROR, "登出失败");
    }

    /**
     * @Author liulianjia
     * @Description 重置密码
     * @Date 2024/12/5 15:46
     **/
    @PutMapping("/rest/password")
    public Result restPassword(@RequestBody InUser user, @RequestHeader(CommonConstant.ACCESS_TOKEN) String token) {
        if (StringUtils.isBlank(user.getPassword())) {
            return Result.err(StatusCode.ERROR_CODE, "参数错误，请参考文档！");
        }
        user.setUserId(JwtUtil.getUserId(token));
        boolean f = userService.restPassword(user, token);
        return f ? Result.success("重置成功，请重新登录！") : Result.err(StatusCode.ERROR, "重置失败");
    }
}
